package com.zwk.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zwk.base.entity.CommonResult;
import com.zwk.base.handler.GuLiException;
import com.zwk.base.util.OrderNoUtil;
import com.zwk.order.client.CourseClient;
import com.zwk.order.client.MemberClient;
import com.zwk.order.entity.Order;
import com.zwk.order.mapper.OrderMapper;
import com.zwk.order.service.OrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author zwk
 * @since 2022-09-01
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private MemberClient memberClient;

    @Autowired
    private CourseClient courseClient;

    // 根据课程id, 用户id生成订单
    @Override
    public String createOrder(String courseId, String memberId) {

        if (ObjectUtils.isEmpty(memberId)){
            throw new GuLiException(20001, "您还没有登录");
        }

        Order order = new Order();
        // 远程调用获取用户信息
        CommonResult memberCommon = memberClient.getMemberInfoById(memberId);
        order.setMemberId((String) memberCommon.getData().get("memberId"));
        order.setNickname((String) memberCommon.getData().get("nickname"));
        order.setMobile((String) memberCommon.getData().get("mobile"));

        // 远程调用获取课程信息
        CommonResult courseCommon = courseClient.getCourseInfoById(courseId);
        order.setCourseId(courseId);
        order.setCourseTitle((String) courseCommon.getData().get("courseTitle"));
        order.setCourseCover((String) courseCommon.getData().get("courseCover"));
        order.setTeacherName((String) courseCommon.getData().get("teacherName"));
        order.setTotalFee(BigDecimal.valueOf((Double) courseCommon.getData().get("coursePrice")));
        order.setStatus(0);
        order.setPayType(1);

        // 设置订单号
        order.setOrderNo(OrderNoUtil.getOrderNo());
        // 添加订单
        int insert = orderMapper.insert(order);
        if (insert == 1){
            return order.getOrderNo();
        }
        throw new GuLiException(20001, "创建订单失败");
    }

    // 根据课程id和用户id查询用户是否购买过该课程
    @Override
    public boolean isBuyCourse(String courseId, String memberId) {
        if (ObjectUtils.isEmpty(memberId)){
            return false;
        }
        QueryWrapper<Order> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id", courseId);
        wrapper.eq("member_id", memberId);
        wrapper.eq("status", 1);
        Integer count = orderMapper.selectCount(wrapper);
        return count > 0;
    }
}
